//
//  MyAdvisoryOrderDetailController.swift
//  EyeVisionForPatients
//
//  Created by PMC on 2020/3/20.
//  Copyright © 2020 tao Tao. All rights reserved.
//

import UIKit

class MyAdvisoryOrderDetailController: BaseViewController {
    
    var handlerClosure: (() -> Void)?
    
    private var detailVM: AdvisoryDetailViewModel? {
        didSet {
            tableView.isHidden = false
            tableView.reloadData()
        }
    }
    
    private var viewModel: MyAdvisoryOrderRowViewModel
    
    init(with vm: MyAdvisoryOrderRowViewModel) {
        self.viewModel = vm
        super.init(nibName: nil, bundle: nil)
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        title = "支付图文咨询"
        loadData()
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        setupNotification()
    }
    
    override func viewDidDisappear(_ animated: Bool) {
        super.viewDidDisappear(animated)
        NotificationCenter.default.removeObserver(self)
    }
    
    @IBOutlet private weak var tableView: UITableView! {
        didSet {
            tableView.isHidden = true  
            tableView.backgroundColor = .background
            tableView.tableFooterView = UIView()
            tableView.register(PublishHeaderViewCell.nibForCell(),
                               forCellReuseIdentifier: PublishHeaderViewCell.reuseIdentifier())
            tableView.register(PublishLabelViewCell.nibForCell(),
                               forCellReuseIdentifier: PublishLabelViewCell.reuseIdentifier())
            tableView.register(PublishTextViewCell.nibForCell(),
                               forCellReuseIdentifier: PublishTextViewCell.reuseIdentifier_0)
            tableView.register(PublishButtonViewCell.nibForCell(),
                               forCellReuseIdentifier: PublishButtonViewCell.reuseIdentifier())
            tableView.register(PublishTextViewCell.nibForCell(),
                               forCellReuseIdentifier: PublishTextViewCell.reuseIdentifier_1)
            tableView.register(PublishTextViewCell.nibForCell(),
                               forCellReuseIdentifier: PublishTextViewCell.reuseIdentifier_2)
            tableView.register(PublishImageViewCell.nibForCell(),
                               forCellReuseIdentifier: PublishImageViewCell.reuseIdentifier())
            tableView.register(NewSectionHeaderView.nibForCell(),
                               forHeaderFooterViewReuseIdentifier: NewSectionHeaderView.reuseIdentifier())
            
            let tap = UITapGestureRecognizer(target: self, action: #selector(endEditing))
            tap.cancelsTouchesInView = false
            tableView.addGestureRecognizer(tap)
        }
    }
    @IBOutlet weak var medicalInsurancePayBtn: UIButton! {
        didSet {
            medicalInsurancePayBtn.setTitle("医保支付", for: .normal)
            medicalInsurancePayBtn.isHidden = true
            medicalInsurancePayBtn.setTitleColor(.white, for: .normal)
            medicalInsurancePayBtn.backgroundColor = .mainColor
            medicalInsurancePayBtn.titleLabel?.font = .regular_12
            medicalInsurancePayBtn.layer.cornerRadius = 15
            medicalInsurancePayBtn.layer.masksToBounds = true
        }
    }
    @IBOutlet private weak var wechatPayBtn: UIButton! {
        didSet {
            wechatPayBtn.setTitle("微信支付", for: .normal)
            wechatPayBtn.setTitleColor(.white, for: .normal)
            wechatPayBtn.backgroundColor = .mainColor
            wechatPayBtn.titleLabel?.font = .regular_12
            wechatPayBtn.layer.cornerRadius = 15
            wechatPayBtn.layer.masksToBounds = true
        }
    }
    @IBOutlet weak var tips: UILabel! {
        didSet {
            tips.font = .regular_12
            tips.textColor = .init(hex: "#666666")
            tips.isHidden = true
        }
    }
    
    @IBAction func medicalInsurancePay(_ sender: Any) {
        submit(type: .medicalInsurancePay)
    }
    @IBAction func wechatPay(_ sender: Any) {
        submit(type: .wechatPay)
    }
    
    private var isAgree: Bool = false
}

// MARK: - 获取数据
extension MyAdvisoryOrderDetailController {
    private func loadData() {
        HUDTool.showActivity()
        AdvisoryDetailViewModel.getPatientAdvisoryDetail(target: ApiManager.advisotyDetail(paras: ["diagnoseId": viewModel.diagnoseId]) , success: { model in
            HUDTool.hideActivity()
            self.detailVM = AdvisoryDetailViewModel(detail: model)
        }) { errorMsg in
            HUDTool.hideActivity()
            HUDTool.showError(message: errorMsg)
        }
        
        MyOrderViewModel.getAdvisoryOrderDetail(orderId: viewModel.orderId, success: { model in
            self.viewModel.orderAmount = model.orderAmount ?? ""
        }) { errorMsg in
            HUDTool.showError(message: errorMsg)
        }
    }
    
    private func setupNotification() {
        NotificationCenter.default.addObserver(self,
                                               selector: #selector(wechatPaySuccess(_:)),
                                               name: NotiName.wechatPaySuccess,
                                               object: nil)
        NotificationCenter.default.addObserver(self,
                                               selector: #selector(wechatPayFailure(_:)),
                                               name: NotiName.wechatPayFailure,
                                               object: nil)
    }
}

// MARK: - Action
extension MyAdvisoryOrderDetailController {
    @IBAction private func viewAgreementAction(_ sender: UIButton) {
        let agreementView = UINib.loadViewFrom(AgreementAlertView.self)
        agreementView.show(type: .agreementLetter)
    }
    
    @IBAction private func agreeAction(_ sender: UIButton) {
        sender.isSelected.toggle()
        isAgree = sender.isSelected
    }
    
    func submit(type: NewAdvisoryGenerateOrderEnum) {
        if !isAgree {
            HUDTool.show(message: "确定知情同意书及平台免责声明")
            return
        }
        switch type {
        case .wechatPay:
            wechatSubmitOrder(viewModel)
        case .medicalInsurancePay:
            medicalInsurancePay(vm: viewModel)
        }
    }
    
    @objc private func endEditing() {
        tableView.endEditing(true)
    }
}

// MARK: - 支付
extension MyAdvisoryOrderDetailController {
    
    private func medicalInsurancePay(vm: MyAdvisoryOrderRowViewModel) {
        guard let query = "id=\(vm.orderId)&token=\(UserDefaults.token)".addingPercentEncoding(withAllowedCharacters: .afURLQueryAllowed),
              let url = URL(string: "alipays://platformapi/startapp?appId=2021003169675062&page=&query=\(query)") else { return }
        if UIApplication.shared.canOpenURL(url) {
            UIApplication.shared.open(url)
        }else{
            YSGToast.showToast(text: "需安装支付宝APP后使用", type: .warring)
        }
    }
    
    /// 微信支付统一下单
    private func wechatSubmitOrder(_ vm: MyAdvisoryOrderRowViewModel) {
        HUDTool.showActivity()
        WXApiRequestHandler.wxPaySubmitOrder(orderId: vm.orderId,
                                             orderAmount: vm.orderAmount,
                                             orderType: .advisory,
                                             success: { wxModel in
            HUDTool.hideActivity()
            switch wxModel.getType {
            case 1:
                self.showSelectPayStyleView(wxModel)
            case 4:
                HUDTool.show(message: "医保已全额支付")
                self.pushPayResultVc()
            default: break
            }
        }) { (errorMsg, code) in
            HUDTool.hideActivity()
            HUDTool.showError(message: errorMsg)
        }
    }
    
    /// 选择支付方式
    private func showSelectPayStyleView(_ model: WXPayResult) {
        let styleView = UINib.loadViewFrom(SelectPayStyleView.self)
        styleView.show()
        styleView.configure(cost: model.ownAmount, time: "30")
        styleView.handlerClosure = { [weak self] style in
            switch style {
            case .wechat:
                self?.wechatPay(model)
            }
        }
    }
    
    /// 微信支付
    private func wechatPay(_ model: WXPayResult) {
        if !WXApi.isWXAppInstalled() {
            HUDTool.show(message: "未安装微信")
            return
        }
        
        WXApiRequestHandler.generateWXPayOrder(model: model)
    }
    
    @objc private func wechatPaySuccess(_ noti: Notification) {
        HUDTool.showActivity()
        PayViewModel.queryOrderStatus(orderId: viewModel.orderId) { (errorMsg) in
            HUDTool.hideActivity()
            if errorMsg != nil {
                HUDTool.show(message: "订单支付失败")
                self.navigationController?.popViewController(animated: true)
            } else {
                self.pushPayResultVc()
            }
        }
    }
    
    @objc private func wechatPayFailure(_ noti: Notification) {
        HUDTool.show(message: "订单支付失败")
        navigationController?.popViewController(animated: true)
    }
}

// MARK: - Helpers
extension MyAdvisoryOrderDetailController {
    private func pushPayResultVc() {
        var vm = PublishViewModel()
        vm.doctorName = viewModel.doctorName
        vm.departmentName = viewModel.departmentName
        let payResultVc = PayResultViewController(with: vm, orderType: .advisory)
        navigationController?.pushViewController(payResultVc, animated: true)
        payResultVc.handlerClosure = { [weak self] in
            guard let self = self else { return }
            self.handlerClosure?()
            self.navigationController?.popViewController(animated: true)
        }
    }
}

// MARK: - DateSource & Delegate
extension MyAdvisoryOrderDetailController: UITableViewDataSource, UITableViewDelegate {
    func numberOfSections(in tableView: UITableView) -> Int {
        return 6
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        switch section {
        case 0: return 2
        case 3: return detailVM?.isAllergyHistory == true ? 2 : 1
        default: return 1
        }
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        switch indexPath.section {
        case 0: return firstSectionCell(at: indexPath)
        case 1: return secondSectionCell(at: indexPath)
        case 2: return thirdSectionCell(at: indexPath)
        case 3: return fourthSectionCell(at: indexPath)
        case 4: return fifthSectionCell(at: indexPath)
        case 5: return sixthSectionCell(at: indexPath)
        default: return UITableViewCell()
        }
    }
    
    func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
        switch section {
        case 0:
            let footer = UINib.loadViewFrom(YSGPublishRuleView.self)
            footer.configure(with: .advisory)
            return footer
        default: return nil
        }
    }
    
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        switch section {
        case 2, 4, 5:
            let header = tableView.dequeueReusableHeaderFooterView(withIdentifier: NewSectionHeaderView.reuseIdentifier()) as? NewSectionHeaderView
            header?.configure(at: section)
            return header
        default:
            return UIView()
        }
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        switch indexPath.section {
        case 0: return indexPath.row == 0 ? 96 : 44
        case 1: return 44
        case 2: return 150
        case 3: return indexPath.row == 0 ? 44 : 80
        case 4: return 100
        case 5: return 250
        default: return 0
        }
    }
    
    func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        switch section {
        case 0: return 78
        default: return 0.001
        }
    }
    
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        switch section {
        case 0: return 0.001
        case 2, 4, 5: return 36
        default: return 16
        }
    }
}

// MARK: - init cell
extension MyAdvisoryOrderDetailController {
    private func firstSectionCell(at indexPath: IndexPath) -> UITableViewCell {
        if indexPath.row == 0 {
            let cell = tableView.dequeueReusableCell(withIdentifier: PublishHeaderViewCell.reuseIdentifier(),
                                                                 for: indexPath) as! PublishHeaderViewCell
            if let detailVm = detailVM {
                cell.configure(advisoryOrder: viewModel, patientDetail: detailVm)
            }
            return cell
        } else {
            let cell = tableView.dequeueReusableCell(withIdentifier: PublishLabelViewCell.reuseIdentifier(),
                                                                 for: indexPath) as! PublishLabelViewCell
            if let detailVm = detailVM {
                cell.configure(with: viewModel, patientDetail: detailVm, indexPath: indexPath)
            }
            return cell
        }
    }
    
    private func secondSectionCell(at indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: PublishLabelViewCell.reuseIdentifier(),
                                                 for: indexPath) as! PublishLabelViewCell
        if let detailVm = detailVM {
            cell.configure(with: viewModel, patientDetail: detailVm, indexPath: indexPath)
        }
        return cell
    }
    
    private func thirdSectionCell(at indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: PublishTextViewCell.reuseIdentifier_0) as! PublishTextViewCell
        if let vm = detailVM {
            cell.configure(with: vm, indexPath: indexPath)
        }
        return cell
    }
    
    private func fourthSectionCell(at indexPath: IndexPath) -> UITableViewCell {
        if indexPath.row == 0 {
            let cell = tableView.dequeueReusableCell(withIdentifier: PublishButtonViewCell.reuseIdentifier(),
                                                     for: indexPath) as! PublishButtonViewCell
            if let vm = detailVM {
                cell.update(advisoryOrder: vm)
            }
            return cell
        } else {
            let cell = tableView.dequeueReusableCell(withIdentifier: PublishTextViewCell.reuseIdentifier_1,
                                                     for: indexPath) as! PublishTextViewCell
            if let vm = detailVM {
                cell.configure(with: vm, indexPath: indexPath)
            }
            return cell
        }
    }
    
    private func fifthSectionCell(at indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: PublishTextViewCell.reuseIdentifier_2,
                                                 for: indexPath) as! PublishTextViewCell
        if let vm = detailVM {
            cell.configure(with: vm, indexPath: indexPath)
        }
        return cell
    }
    
    private func sixthSectionCell(at indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: PublishImageViewCell.reuseIdentifier(),
                                                 for: indexPath) as! PublishImageViewCell
        if let vm = detailVM {
            let imageModels = vm.detailImages.map { model -> UploadImgModel in
                return UploadImgModel(resourceId: model.resourceId,
                                      ShareThumbnailUrl: model.thumbnailUrl,
                                      shareThumbnailUrl: model.thumbnailUrl,
                                      shareUrl: model.url)
            }
            let publishVm = PublishViewModel(models: imageModels, deleteEnabled: false)
            cell.configure(with: publishVm, delegate: nil)
        }
        return cell
    }
}
